<template>
  <div>
    <FixedOperation v-if="!isDialog">
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container repayment-plan-form">
      <el-form
        ref="form"
        :model="formData"
        label-width="140px"
        :rules="formRules"
      >
        <el-row>
          <el-col
            :span="isDialog ? 24 : 12"
            v-if="false"
            :offset="isDialog ? '' : 5"
          >
            <el-form-item label="id" prop="uuid">
              <el-input disabled v-model="formData.uuid" placeholder="id" />
            </el-form-item>
          </el-col>
          <el-col :span="isDialog ? 24 : 12" :offset="isDialog ? '' : 5">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                class="w-full"
                v-model="formData.customerId"
                placeholder="请选择客户名称"
                @focus="selectCustomerFn('customerId')"
              >
                <el-option
                  v-for="item in customerOption['customerId']"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
              <!-- <el-select
                v-model="formData.customerId"
                placeholder="请选择客户名称"
                class="w-full"
                filterable
                remote
                clearable
                @change="changeCustomer"
                :remote-method="queryCustomer"
                :loading="!parentOptions"
              >
                <el-option
                  v-for="item in parentOptions"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                >
                  <div>
                    <span>{{ item.customerName }}</span>
                    <span>({{ item.mainContactName }})</span>
                  </div>
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="isDialog ? 24 : 12" :offset="isDialog ? '' : 5">
            <el-form-item label="关联订单" prop="orderTitle">
              <el-input
                @click="activeDialog"
                placeholder="请选择关联订单"
                v-model="formData.orderTitle"
                clearable
                @clear="clearAll"
              ></el-input>
              <!-- <el-select
                v-model="formData.orderId"
                placeholder="请输入订单名称检索订单"
                class="w-full"
                suffix-icon="Search"
                remote-show-suffix
                :suffix-transition="false"
                filterable
                remote
                clearable
                @change="changeIndent"
                :remote-method="
                  val => queryIndentLimitEnt(val, formData.customerId)
                "
                :loading="loadingSelect"
              >
                <el-option
                  v-for="item in indentOptionLimitEnt"
                  :key="item.orderId"
                  :label="item.orderTitle"
                  :value="item.orderId"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="isDialog ? 24 : 12" :offset="isDialog ? '' : 5">
            <el-form-item label="订单总金额" prop="totalPrice">
              <el-input
                disabled
                v-model="formData.totalPrice"
                placeholder="请输入订单总金额"
                ><template v-slot:append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="isDialog ? 24 : 12" :offset="isDialog ? '' : 5">
            <el-form-item label="签单日期" prop="signDate">
              <el-date-picker
                disabled
                v-model="formData.signDate"
                type="date"
                placeholder="签单日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="isDialog ? 24 : 16" :offset="isDialog ? '' : 4">
            <avue-crud
              ref="crud"
              :option="crudOption"
              :data="formData.repaymentPlanList"
            >
              <template #menu-left> </template>
              <template #period="{ row }">
                <span>{{ rowIndex(row) }}</span>
              </template>
              <template #menu="{ row, index }">
                <el-button plain icon="Delete" link @click="delRow(row, index)"
                  >删除</el-button
                >
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
              <template #footer>
                <el-col :span="24" class="py-2 text-right">
                  总计划期次： {{ formData.repaymentPlanList.length }}期
                  总回款占比：{{ formData.proportion }}% 总回款金额：¥
                  {{ formData.totalPricePlan }}
                </el-col>
                <el-button
                  plain
                  type="primary"
                  icon="Plus"
                  class="w-full"
                  @click="addRow"
                  >添加期次</el-button
                >
              </template>
            </avue-crud>
          </el-col></el-row
        >
      </el-form>
    </div>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    ></SelectCustomer>

    <!-- 关联订单弹窗 -->
    <RelatedOrder
      :relatedParams="orderParams"
      @closeDialog="closeDialog"
      @relatedOver="relatedOver"
    />
  </div>
</template>
<script setup name="RepaymentPlanForm">
import { reactive, toRefs, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import usePassData from '@/store/modules/passData'
import FixedOperation from '@/components/FixedOperation'
import useCommonStore from '@/store/modules/common'
import {
  getRepaymentPlanOrderId,
  setRepaymentPlan,
  delRepaymentPlan
} from '@/api/repaymentManage/repayment'
import { listSalesOrderSelect } from '@/api/indentManage/indent'
import {
  loadingSelect, //远程检索loading
  indentOptionLimitEnt, // 订单数据
  queryIndentLimitEnt // 检索订单数据
} from '@/hooks/dict/order'
import useTagsViewStore from '@/store/modules/tagsView'
import { isMoneyNot, isNum } from '@/utils/validate'
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})
const { pay_type, settle_type } = proxy.useDict('pay_type', 'settle_type')

const props = defineProps({
  repaymentPlanData: {
    type: Object,
    require: false,
    default: null
  },
  orderId: {
    type: [String, Number],
    require: false,
    default: null
  },
  isDialog: {
    type: Boolean,
    require: false,
    default: false
  }
})
const isDialog = ref(false)
const data = reactive({
  formData: {
    repaymentPlanList: [],
    totalPrice: 0,
    proportion: 0,
    customerType: 'customer'
  },
  crudOption: {
    header: false,
    menu: true,
    delBtn: false,
    editBtn: false,
    addBtn: false,
    addRowBtn: false,
    saveBtn: false,
    cancelBtn: false,
    cellBtn: false,
    // searchBtn: false,
    refreshBtn: false,
    columnBtn: false,
    menuWidth: 80,
    column: [
      {
        label: '期次',
        prop: 'period',
        width: '50',
        rules: [
          {
            required: true,
            message: '期次',
            trigger: 'blur'
          }
        ],
        value: '1',
        cell: false
      },
      {
        label: '计划回款日期',
        prop: 'repaymentPlanDate',
        type: 'date',
        cell: true,
        valueFormat: 'YYYY-MM-DD',
        rules: [
          {
            required: true,
            message: '请输入计划回款日期',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '计划回款占比(%)',
        prop: 'proportion',
        type: 'number',
        min: 0,
        max: 100,
        class: 'w-full',
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入计划回款占比(%)',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '计划回款金额(元)',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入计划回款金额(元)',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        cell: true
      },
      {
        label: '付款方式',
        prop: 'payType',
        type: 'select',
        dicData: pay_type,
        rules: [
          {
            required: true,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '结算方式',
        prop: 'settleType',
        type: 'select',
        dicData: settle_type,
        rules: [
          {
            required: true,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '备注',
        prop: 'remark',
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },

  formRules: {
    customerId: [
      {
        required: true,
        message: '请输入客户名称',
        trigger: 'change'
      }
    ],
    orderId: [
      {
        required: true,
        message: '请输入关联订单',
        trigger: 'change'
      }
    ],
    orderTitle: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ]
  },
  customerOption: {}, //客户选择下拉
  dialogParamA: {} /* 客户弹窗框参数 */
})
const { formData, crudOption, formRules, customerOption, dialogParamA } =
  toRefs(data)
watch(
  () => data.formData.repaymentPlanList,
  (newVal, oldValue) => {
    let price = 0
    let proportion = 0
    formData.value.repaymentPlanList.forEach(e => {
      price = Number(e.price) + Number(price)
      proportion = Number(e.proportion) + Number(proportion)
    })
    formData.value.totalPricePlan = price
    formData.value.proportion = proportion
  },
  { deep: true }
)
watch(
  [() => route.query.salesOrderId, () => props.orderId],
  () => {
    if (route.query.salesOrderId && route.name == type.name) {
      getFormData(route.query.salesOrderId)
    }
    if (props.orderId) {
      getFormData(props.orderId)
    }
  },
  {
    immediate: true
  }
)
/** 获取回款计划
 * @param {number}  id 表单id
 */
function getFormData(id) {
  proxy.$modal.loading('加载中')
  getRepaymentPlanOrderId(id).then(res => {
    let resData = {}
    resData = res.data
    customerOption.value['customerId'] = [
      {
        label: resData.customerName, //? resData.customerName: resData.customerId,
        id: resData.customerId //? resData.customerId : resData.customerName
      }
    ]
    indentOptionLimitEnt.value = [
      {
        orderTitle: resData.orderTitle,
        orderId: resData.orderId
      }
    ]
    resData.repaymentPlanList.forEach((e, i) => {
      if (e.id) {
        resData.repaymentPlanList[i].$cellEdit = true
      }
    })
    proxy.$modal.closeLoading()
    formData.value = resData
  })
}

// 回款计划期次赋值
function rowIndex(row) {
  row.period = row.$index + 1
  return row.$index + 1
}

// 初始化
function init() {
  isDialog.value = props.isDialog
}
function handleSubmit(e) {
  return new Promise((resolve, reject) => {
    proxy.$refs.form.validate((valid, done, msg) => {
      proxy.$refs.crud.validateCellForm().then(err => {
        if (valid && !err) {
          setRepaymentPlan(formData.value).then(res => {
            // proxy.$modal.msgSuccess(formData.value.uuid ? '修改成功' : '新增成功')
            // if (!formData.value.id) {
            //   useTagsViewStore().delView(router.currentRoute.value)
            //   router.go(-1)
            // }
            // 保存接口才有
            resolve(res)
            if (!isDialog.value) {
              proxy.useReturn(
                '',
                () => {
                  //返回上一步
                  handleReturn()
                },
                async () => {
                  //继续
                }
              )
            }
            let repaymentPlanList = res.data.repaymentPlanList.map(e => {
              return {
                ...e,
                $cellEdit: true
              }
            })
            formData.value = { ...res.data, repaymentPlanList }
            console.log('formData.value==>', formData.value)
          })
        }
      })
    })
  })
}

function handleReset() {
  console.log('清除')
  formData.value = {
    repaymentPlanList: [],
    totalPrice: 0,
    proportion: 0
  }
  proxy.resetForm('sortRef')
  //   proxy.$refs.form.resetForm()
}

// 改变客户名称后
const changeCustomer = val => {
  formData.value.orderId = null
  formData.value.orderTitle = null
  // queryIndentLimitEnt(undefined, val)
}

/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = formData.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
  }
}

// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      if (formData.value.customerId !== val.defaultCheckedKeys.toString()) {
        changeCustomer(val.defaultCheckedKeys.toString())
      }
      formData.value.customerType = val.tabVal
      formData.value.customerName = val.labelData.toString()
      formData.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

// 订单赋值
function changeIndent(val) {
  console.log('val==>', val)
  indentOptionLimitEnt.value.forEach(item => {
    if (val == item.orderId) {
      formData.value.totalPrice = item.totalPrice
      formData.value.signDate = item.signDate
      if (item.repaymentPlanList) {
        formData.value.repaymentPlanList = item.repaymentPlanList.map(item => {
          return { ...item, $cellEdit: true }
        })
      }
      console.log('item==>', item)
      console.log(
        'formData.value.repaymentPlanList==>',
        formData.value.repaymentPlanList
      )
    }
  })
}
// 添加期次
function addRow() {
  formData.value.repaymentPlanList.push({ $cellEdit: true, price: 0 })
  console.log('product==>', formData.value.repaymentPlanList)
}
// 删除行
function delRow(row, index, done) {
  proxy
    .$confirm('是否删除该回款计划', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      if (row.id) {
        delRepaymentPlan(row.id).then(e => {
          formData.value.repaymentPlanList.splice(index, 1)
          proxy.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      } else {
        formData.value.repaymentPlanList.splice(index, 1)
        proxy.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    })
    .catch(() => {})
}

/****    关联订单  开始   ***/
// 弹窗参数
const orderParams = ref()
// 打开弹窗
function activeDialog() {
  const id = formData.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择客户名称')
    return false
  }
  const ids = [formData.value.orderId]
  console.log('ids==>', ids)
  orderParams.value = {
    visible: true, // 显示dialog
    businessId: id, // 根据id查询订单
    businessName: formData.value.customerName,
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
}

// 弹窗确认完成回调
function relatedOver(val) {
  if (val) {
    const name = orderParams.value.multiple
      ? val.map(v => v.orderTitle).toString() || ''
      : val.orderTitle

    const ids = orderParams.value.multiple
      ? val.map(v => v.orderId) || []
      : val.orderId

    formData.value.orderId = ids
    formData.value.orderTitle = orderParams.value.multiple
      ? val.map(v => v.orderTitle)
      : name
    console.log(formData.value.orderTitle, ' formData.value.orderTitle')
  }
  closeDialog()
}

// 关闭弹窗
function closeDialog() {
  orderParams.value.visible = false
}

// el-input clear函数
function clearAll() {
  formData.value.orderId = null
  formData.value.orderTitle = null
}
/****    关联订单  end   ***/

// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

//暴露出保存方法
defineExpose({ handleSubmit })
init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.repayment-plan-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}
:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
